<?php

class ClipController extends FrontController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','hot','new','jview','jlist'),
				'users'=>array('*'),
			),
//			array('allow', // allow authenticated user to perform 'create' and 'update' actions
//				'actions'=>array('create','update'),
//				'users'=>array('@'),
//			),
//			array('allow', // allow admin user to perform 'admin' and 'delete' actions
//				'actions'=>array('admin','delete'),
//				'users'=>array('admin'),
//			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model=$this->loadModel($id);
		$criteriaF=new CDbCriteria();
		$criteriaF->condition = 't.id != '.$model->id.' AND cid='.$model->cid.' AND t.active=1';
		//$criteriaF->order='t.order DESC';RAND()
		$criteriaF->order='RAND()';
		$dataProviderF=new CActiveDataProvider('Clip', array(
    		'criteria'=>$criteriaF,
			'pagination'=>array(
		      'pageSize'=>5,
		    ),
		));
		$this->render('view',array(
			'model'=>$model,
			'dataProvider'=>$dataProviderF,
		));
	}
	public function actionJview($id){
		if(isset($_POST['user']) && isset($_POST['passwd'])){
			if(($_POST['user'] === 'mbapp') && ($_POST['passwd'] === '6EVAje6U')){
				$model = $this->loadModel($id);
				header('Content-type: application/json');
			
				$jsondata = array('clipdetail' =>$model,
				);
				echo CJSON::encode($jsondata);
				Yii::app()->end();
			}
		}
	}
	public function actionJlist()
	{
		if(isset($_POST['user']) && isset($_POST['passwd'])){
			if(($_POST['user'] === 'mbapp') && ($_POST['passwd'] === '6EVAje6U')){
				$Ccriteria=new CDbCriteria();
				$Ccriteria->condition = "t.active=1";
				$Ccriteria->order='t.order DESC';
				$CdataProvider=new CActiveDataProvider('Clip', array(
						'criteria'=>$Ccriteria,
						'pagination'=>array(
								'pageSize'=>10,
						),
				));
				header('Content-type: application/json');
		
				$jsondata = array('cliphome' =>$CdataProvider->getData(),
						'pageinfo'=>array(
								array(
										'pagecount'=>$CdataProvider->getPagination()->getPageCount(),
										'currentpage'=>$CdataProvider->getPagination()->currentPage,
								)
						));
				echo CJSON::encode($jsondata);
				Yii::app()->end();
			}
		}
	}
	/*public function actionView($id)
	{
		$member=new Member;
		$show=Tools::is3G();
		$key=Yii::app()->request->getParam('key',0);
		if($key!=0){
			$temp=Temp::model()->findByPk($key);
			if($temp!=null){
				$mem=Member::model()->findByAttributes(array('username'=>$temp->val));
				$temp->delete();
				$login=new FrontLoginForm;
				$login->username=$mem->username;
				$login->password=$mem->password;
				$login->rememberMe=true;
				$login->login();
				//Yii::app()->user->setFlash('success', "<b>Tài khoản:</b> ".$model->username."<br/> <b>Mật khẩu:</b> ".$model->password.".<br/> Hãy thay đổi mật khẩu sau lần đăng nhập đầu tiền.  Cảm ơn bạn đã sử dụng dịch vụ của MobileTV.");
			}
				
		}
		if(Yii::app()->user->id!==null){
			$member=Member::model()->findByPk(Yii::app()->user->id);
			$model=$this->loadModel($id);
			$trans=Transclip::model()->findByAttributes(array('mid'=>$member->id,'cid'=>$model->id));
			if($trans==null){
				if($member->amount >= $model->retail[0]['price']){
					// Save transaction
					$trans=new Transclip();
					$trans->mid=$member->id;
					$trans->cid=$model->id;
					$trans->price=$model->retail[0]['price'];
					$trans->startdate=date('Y-m-d H:i');
					$trans->enddate=date('Y-m-d H:i');
					$trans->active=1;
					if($trans->save()){
						$member->amount=$member->amount-$model->retail[0]['price'];
						if($member->save()){
							$criteriaF=new CDbCriteria();
							$criteriaF->condition = 't.id != '.$model->id.' AND cid='.$model->cid.' AND t.active=1';
							$criteriaF->order='t.order DESC';
							$dataProviderF=new CActiveDataProvider('Clip', array(
					    		'criteria'=>$criteriaF,
								'pagination'=>array(
							      'pageSize'=>5,
							    ),
							));
							$this->render('view',array(
								'model'=>$model,
								'dataProvider'=>$dataProviderF,
							));
						}
					}
				}
				else{
					if($show!=''){
						$Session= new Session('Script');
						$Session->set('fs',time());
						$Session->set('id',$model->id);
						$appid=Yii::app()->params['applicationId'];
						$appsecret=Yii::app()->params['appSecret'];
						$p='clip_'.$model->id;
						$s=$Session->Get('fs');
						$md5=md5($appid.$p.$appsecret.$s);
						$link=Yii::app()->params['paymentUrl'].'?a='.$appid.'&p='.$p.'&s='.$s.'&md5='.$md5;
						$this->redirect($link);
					}
					else {
						Yii::app()->user->setFlash('warning', "Tài khoản của bạn hiện không đủ để xem clip này. Xin vui lòng nạp thêm tiền vào tài khoản.");
						$this->redirect(array('/member/about'));
					}
				}
			}
			else{
				$criteriaF=new CDbCriteria();
				$criteriaF->condition = 't.id != '.$model->id.' AND cid='.$model->cid.' AND t.active=1';
				$criteriaF->order='t.order DESC';
				$dataProviderF=new CActiveDataProvider('Clip', array(
		    		'criteria'=>$criteriaF,
					'pagination'=>array(
				      'pageSize'=>5,
				    ),
				));
				$this->render('view',array(
					'model'=>$model,
					'dataProvider'=>$dataProviderF,
				));
			}
		}
		else{
			$model=$this->loadModel($id);
			if($model->retail[0]['price']==0){
				$criteriaF=new CDbCriteria();
				$criteriaF->condition = 't.id != '.$model->id.' AND cid='.$model->cid.' AND t.active=1';
				$criteriaF->order='t.order DESC';
				$dataProviderF=new CActiveDataProvider('Clip', array(
						'criteria'=>$criteriaF,
						'pagination'=>array(
								'pageSize'=>5,
						),
				));
				$this->render('view',array(
						'model'=>$model,
						'dataProvider'=>$dataProviderF,
				));
			}
			else{
				if($show!=''){
					$Session= new Session('Script');
					$Session->set('fs',time());
					$Session->set('id',$id);
					$appid=Yii::app()->params['applicationId'];
					$appsecret=Yii::app()->params['appSecret'];
					$p='clip_'.$id;
					$s=$Session->Get('fs');
					$md5=md5($appid.$p.$appsecret.$s);
					$link=Yii::app()->params['paymentUrl'].'?a='.$appid.'&p='.$p.'&s='.$s.'&md5='.$md5;
					$this->redirect($link);
				}
				else{
					$this->redirect(array('/site/login'));
				}
			}
		}
	}
	*/
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 
	public function actionCreate()
	{
		$model=new Clip;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Clip']))
		{
			$model->attributes=$_POST['Clip'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
	*/
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Clip']))
		{
			$model->attributes=$_POST['Clip'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	*/
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	*/
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        //New
        $criteriaNew = new CDbCriteria();
        $criteriaNew->limit = 5;
        $criteriaNew->order = 't.order DESC';
        $dataProviderNew = new CActiveDataProvider('Clip', array(
            'criteria' => $criteriaNew,
            'pagination' => false,
        ));

        //get list clip category for render clip dataprovider
        $criteriaCatClip = new CDbCriteria();
        $criteriaCatClip->select = array('id', 'name');
        $criteriaCatClip->order = 't.order ASC';
        $clipCategory = Clipcategory::model()->findAll($criteriaCatClip);

        $dataProviderClipArr = array();
        foreach ($clipCategory as $clipCategoryData) {
            $dataProviderClip = new CActiveDataProvider('Clip', array(
                'criteria' => array(
                    'order' => 't.id DESC',
                    'condition' => 'cid = ' . $clipCategoryData->id,
                    'limit' => 5,
                ),
                'pagination' => false,
            ));
            //push dataprovider to cliparr
            array_push($dataProviderClipArr, $dataProviderClip);
        }

        $this->render('index', array(
            'dataProviderNew' => $dataProviderNew,
            'dataProviderClipArr' => $dataProviderClipArr,
            'clipCategory' => $clipCategory,
        ));
		
	}
	
	/**
	 * Lists all models new.
	 */
	public function actionNew()
	{
		//New
		$criteriaNew=new CDbCriteria();
		$criteriaNew->condition = "t.active=1";
		$criteriaNew->order='t.id DESC';
		$dataProviderNew=new CActiveDataProvider('Clip', array(
    		'criteria'=>$criteriaNew,
			'pagination'=>array(
			      'pageSize'=>10,
			),
		));
		$this->render('new',array(
			'dataProviderNew'=>$dataProviderNew,
		));
	}
	
	/**
	 * Lists all models hot.
	 */
	public function actionHot()
	{
		//Hot
		$criteriaHot=new CDbCriteria();
		$criteriaHot->condition = "t.global_hot=1 AND t.active=1";
//		$criteriaHot->limit = 5;
		$criteriaHot->order='t.order ASC';
		$dataProviderHot=new CActiveDataProvider('Clip', array(
    		'criteria'=>$criteriaHot,
			'pagination'=>array(
			      'pageSize'=>10,
			),
		));
		$this->render('hot',array(
			'dataProviderHot'=>$dataProviderHot,
		));
	}
	/**
	 * Manages all models.
	 
	public function actionAdmin()
	{
		$model=new Clip('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Clip']))
			$model->attributes=$_GET['Clip'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	*/
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Clip::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='clip-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
